<template>
    <div id="webskt">
        <h1>websocket 调试</h1>
        <!-- <form> -->
        <input name="content" value="">
        <button type="reset">点击重置</button>
        <!-- <button v-on:click="connect">连接</button> -->
        <button v-on:click="close">关闭</button>
        <button v-on:click="send">发送</button>

        <!-- </form> -->
    </div>
</template>
<script>
let websocket;


// websocket.onclose = function (evt) {
//     console.log("Disconnected");
// };

// websocket.onmessage = function (evt) {
//     console.log('Retrieved data from server: ' + evt.data);
// };

// websocket.onerror = function (evt, e) {
//     console.log('Error occured: ' + evt.data);
// };

export default {
    name: 'WebSocket',
    data() {
        return {
            wsCfg:{
                url:'ws://192.168.100.230:9502?userid=12&token=1111222334455isldfslfj'
            }
        }
    },
    methods: {
        createWebSocket() {
            try {
                // 创建Web Socket 连接
                websocket = new WebSocket(this.wsCfg.url);
                // 初始化事件
                this.initEventHandle(websocket);
            } catch (e) {
                // 出错时重新连接
                this.reconnect(this.wsCfg.url);
            }
        },
        initEventHandle(socket) {
            // 连接关闭时触发
            socket.onclose = () => {
                console.log("连接关闭");
            };
            // 通信发生错误时触发
            socket.onerror = () => {
                // 重新创建长连接
                this.reconnect();
            };
            // 连接建立时触发
            socket.onopen = () => {
                console.log("连接成功");
            };
            // 客户端接收服务端数据时触发
            socket.onmessage = msg => {
                // 业务逻辑处理
                console.log(msg.data, "ws:data");
            };
        },
        send() {
            websocket.send("ssss");
        },
        reconnect() {
            if (this.lockReconnect) {
                return;
            }
            this.lockReconnect = true;

            // 没连接上会一直重连，设置延迟避免请求过多
            setTimeout(() => {
                this.lockReconnect = false;
                this.createWebSocket(this.wsCfg.url);
            }, 2000);
        },
        close(){
            websocket.close();
        }
    },
    mounted() {
        this.createWebSocket();
    }
}


</script>